package data;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

public class Book 
{
	public static final String NAME = "Name";
	public static final String ISBN = "ISBN";
	public static final String PUBLISHER = "Publisher";
	private static final String SEPARATOR = ";";
	private static final String ASSIGN = "=";
	private static final String PARENT = "Book";
	
	private String m_strName = null;
	private String m_strPublisher = null;
	private int m_nIsbn = -1;
	
	public Book(String strContent)
	{
		Transform(strContent);
	}
	
	public Book(Entity entBook)
	{
		Object oValue = entBook.getProperty(NAME);
		if (oValue != null)
			m_strName = oValue.toString();
		else
			throw new IllegalArgumentException("Unavailable property name in Book:" + NAME);
		
		oValue = entBook.getProperty(PUBLISHER);
		if (oValue != null)
			m_strPublisher = oValue.toString();
		else
			throw new IllegalArgumentException("Unavailable property name in Book:" + PUBLISHER);
		
		oValue = entBook.getProperty(ISBN);
		if (oValue != null)
		{
			try
			{
				m_nIsbn = Integer.valueOf(oValue.toString());
			}
			catch (NumberFormatException e)
			{
				throw new IllegalArgumentException("Invalid ISBN format in Book");
			}
		}
		else
			throw new IllegalArgumentException("Unavailable property name in Book:" + ISBN);
			
	}
	
	public Entity GetEntity(Key key) 
	{
		Entity entBook = new Entity(PARENT, key);
		entBook.setProperty(NAME, m_strName);
		entBook.setProperty(ISBN, m_nIsbn);
		entBook.setProperty(PUBLISHER, m_strPublisher);
		return entBook;
	}
	
	private void Transform(String strContent)
	{
		String[] straSplit = strContent.split(SEPARATOR);
		for (String strSplit : straSplit)
		{
			String[] straToken = strSplit.trim().split(ASSIGN);
			if (straToken.length != 2) //illegal pattern
				throw new IllegalArgumentException("Invalid format in Book:" + strSplit);

			switch(straToken[0])
			{
				case NAME:
					m_strName = straToken[1];
					break;
				case PUBLISHER:
					m_strPublisher = straToken[1];
					break;
				case ISBN:
					try
					{
						m_nIsbn = Integer.valueOf(straToken[1]);
					}
					catch (NumberFormatException e)
					{
						throw new IllegalArgumentException("Invalid format in Book:" + strSplit);
					}
					break;
				default:
					throw new IllegalArgumentException("Invalid format in Book:" + strSplit);
			}
		}
		
		if (m_strName == null || m_strPublisher == null || m_nIsbn == -1 )
			throw new IllegalArgumentException("invalid format in Book:" + strContent);
	}
	
	public String toString()
	{
		return NAME + ASSIGN + m_strName + SEPARATOR + 
				    PUBLISHER + ASSIGN + m_strPublisher + SEPARATOR +
				    ISBN + ASSIGN + m_nIsbn;
	}
	

}
